package logic

import (
	"context"
	"doctor-medicine-system/doctorrpc/doctorrpc"
	"doctor-medicine-system/doctorrpc/internal/svc"
	"doctor-medicine-system/model/mysql"
	"doctor-medicine-system/pkg"
	"errors"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录认证
func (l *LoginLogic) Login(in *doctorrpc.LoginRequest) (*doctorrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	user := &mysql.User{
		Username: in.Username,
		Password: pkg.Md5Str(in.Password),
	}

	err := user.FindUserByUsername(mysql.DB, in.Username)
	if err != nil {
		return nil, err
	}

	if pkg.Md5Str(in.Password) != user.Password {
		return nil, errors.New("密码错误，请重新输入")
	}

	return &doctorrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
